import BaseHTTPServer
import functools
import json
import multiprocessing

import cfg
import nfa

class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
  def do_POST(self):
    # print(self.path)
    # print(multiprocessing.current_process().name)
    content_length = int(self.headers['Content-Length'])
    post_data = self.rfile.read(content_length)
    # print(post_data)
    o = json.loads(post_data)
    if o['type'] == 'nfa':
      machine = nfa.from_json(o['machine'])
      parser = nfa.parser
    if o['type'] == 'cfg':
      machine = cfg.from_json(o['machine'])
      parser = cfg.parser
    if self.path == '/neighbor':
      neighbor = machine.get_neighbor()
      neighbor.DL = neighbor.description_length()
      response = neighbor.to_json()
      print(response)
      self.wfile.write(response)
    if self.path == '/parse':
      parser = functools.partial(parser, machine_json=o['machine'])
      dls = self.server.pool.map(parser, o['words'])
      print(sum(dls))
      self.wfile.write(json.dumps(dls))

def start_server(port=80):
  try:
    httpd = BaseHTTPServer.HTTPServer(('', port), Handler)
    httpd.pool = multiprocessing.Pool()
    print('serving at port', port)
    httpd.serve_forever()
  except KeyboardInterrupt:
    print '^C received, shutting down the web server'
    httpd.socket.close()

if __name__ == '__main__':
  start_server()
